<template>
  <Dialog v-model="dialogVisible" title="采购计划导入" width="400">
    <el-upload
      ref="uploadRef"
      v-model:file-list="fileList"
      :action="importUrl"
      :auto-upload="false"
      :disabled="formLoading"
      :headers="uploadHeaders"
      :limit="1"
      :on-error="submitFormError"
      :on-exceed="handleExceed"
      :on-success="submitFormSuccess"
      accept=".xlsx, .xls"
      drag
    >
      <Icon icon="ep:upload" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <span>仅允许导入 xls、xlsx 格式文件。</span>
          <el-link
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            type="primary"
            @click="importTemplate"
          >
            下载模板
          </el-link>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { PurchasePlanApi } from '@/api/erp/purchase/plan'
import download from '@/utils/download'
import { nextTick } from 'vue' // 确保nextTick已导入（若原代码未导入）

defineOptions({ name: 'SystemUserImportForm' })

const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const uploadRef = ref()
const importUrl = ref(import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL)
const uploadHeaders = ref() // 上传 Header 头
const fileList = ref([]) // 文件列表
const updateSupport = ref(0) // 是否更新已经存在的用户数据

// 采购类型
const type = ref(undefined)

/** 打开弹窗 */
const open = (purchaseType: any) => {
  type.value = purchaseType
  dialogVisible.value = true
  updateSupport.value = 0
  fileList.value = []
  resetForm()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/* 监听打开窗口的采购类型 */
watch(
  () => type.value,
  (newValue) => {
    // 定义类型到路径的映射关系
    const pathMap = {
      SERVICE: '/erp/purchase-plan/import/service',
      EQUIPMENT: '/erp/purchase-plan/import/equipment',
      ENGINEERING: '/erp/purchase-plan/import/engineering',
      MATERIAL: '/erp/purchase-plan/import/material',
      DIRECT: '/erp/purchase-plan/import/minor',
      MINOR: '/erp/purchase-plan/import/minor'
    }
    // 获取基础URL（移除可能存在的旧路径部分）
    const baseUrl = importUrl.value.split('/erp/')[0]
    // 根据类型获取对应路径
    const path = pathMap[newValue]
    // 更新URL
    if (path) {
      importUrl.value = baseUrl + path
    } else {
      console.warn(`未知的采购类型: ${newValue}`)
    }
  },
  { immediate: true }
)

/** 提交表单 */
const submitForm = async () => {
  if (fileList.value.length == 0) {
    message.error('请上传文件')
    return
  }
  formLoading.value = true
  uploadRef.value!.submit()
}

/** 文件上传成功 */
const emits = defineEmits(['success'])
const submitFormSuccess = (response: any) => {
  if (response.code !== 0) {
    message.error(response.msg)
    formLoading.value = false
    return
  }
  // 拼接提示语
  const data = response.data
  formLoading.value = false
  dialogVisible.value = false
  // 发送操作成功的事件
  emits('success', data)
}

/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')
  formLoading.value = false
}

/** 重置表单 */
const resetForm = async (): Promise<void> => {
  // 重置上传状态和文件
  formLoading.value = false
  await nextTick()
  uploadRef.value?.clearFiles()
}

/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error('最多只能上传一个文件！')
}

/** 下载Excel 模板 */
const importTemplate = async () => {
  try {
    // 1. 新增：采购类型英文标识 -> 中文名称的映射（核心修改）
    const typeCNMap = {
      SERVICE: '服务类',
      EQUIPMENT: '设备类',
      ENGINEERING: '工程类',
      MATERIAL: '物资类',
      DIRECT: '直接采购类', // DIRECT 与 MINOR 均对应零星采购
      MINOR: '小额零星类'
    }
    // 2. 定义API映射关系，减少重复代码
    const apiMap = {
      SERVICE: PurchasePlanApi.exportPurchasePlanServiceTemplate,
      EQUIPMENT: PurchasePlanApi.exportPurchasePlanEquipmentTemplate,
      ENGINEERING: PurchasePlanApi.exportPurchasePlanEngineeringTemplate,
      MATERIAL: PurchasePlanApi.exportPurchasePlanMaterialTemplate,
      DIRECT: PurchasePlanApi.exportPurchasePlanMinorTemplate,
      MINOR: PurchasePlanApi.exportPurchasePlanMinorTemplate
    }
    // 3. 根据类型获取对应的API方法和中文名称
    const apiMethod = apiMap[type.value]
    const typeCN = typeCNMap[type.value] || '采购' // 兜底：若类型未知，显示“采购”
    // 4. 检查类型是否支持
    if (!apiMethod) {
      throw new Error(`不支持的采购类型: ${type.value}`)
    }
    // 5. 调用API获取数据
    const data = await apiMethod()
    // 6. 替换模板名称为中文（核心修改：用中文名称替换英文标识）
    download.excel(data, `${typeCN}采购明细导入模板.xls`)
  } catch (error) {
    // 统一错误处理
    console.error('导出模板失败:', error)
    message.error('导出模板失败，请稍后重试') // 新增用户提示，提升体验
  }
}
</script>